package com.dick.weixin.service;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.dick.weixin.pojo.WeixinGroup;
import com.dick.weixin.util.CommonUtil;
import com.dick.weixin.util.logging.Logger;
import com.dick.weixin.util.logging.LoggerFactory;

/**
 * 类 名 称： WeixinGroupService 类 描 述： 微信分组 创 建 人： zhangyaomin 邮
 * 箱：zhangyaomin@yunchuangyi.cn 创建时间：2014-3-11下午04:49:33
 */
public class WeixinGroupService {
	private static Logger log = LoggerFactory
			.getLogger(WeixinGroupService.class);

	/**
	 * 查询分组
	 * 
	 * @param accessToken
	 *            接口访问凭证
	 * @return
	 */
	@SuppressWarnings( { "unchecked", "deprecation" })
	public static List<WeixinGroup> getGroups(String accessToken) {

		List<WeixinGroup> weixinGroupList = null;
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=ACCESS_TOKEN";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
		JSONObject jsonObject = CommonUtil.httpRequest(requestUrl, "GET", null);
		if (null != jsonObject) {
			try {
				weixinGroupList = JSONArray.toList(jsonObject
						.getJSONArray("groups"), WeixinGroup.class);
			} catch (Exception e) {
				weixinGroupList = null;
				int errorCode = jsonObject.getInt("errcode");
				String errorMsg = jsonObject.getString("errmsg");
				log.error("查询分组失败 errcode:{} errmsg:{}", errorCode + "",
						errorMsg);
				e.printStackTrace();
			}
		}
		return weixinGroupList;
	}

	/**
	 * 创建分组
	 * 
	 * @param accessToken
	 *            接口访问凭证
	 * @param groupName
	 *            分组名
	 * @return
	 */
	public static WeixinGroup createGroup(String accessToken, String groupName) {
		WeixinGroup weixinGroup = null;
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=ACCESS_TOKEN";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
		// 需要提交的JSON数据
		String jsonData = "{\"group\":{\"name\":\"%s\"}}";
		JSONObject jsonObject = CommonUtil.httpRequest(requestUrl, "GET",
				String.format(jsonData, groupName));
		if (null != jsonObject) {
			try {
				weixinGroup = new WeixinGroup();
				weixinGroup.setId(jsonObject.getJSONObject("group")
						.getInt("id"));
				weixinGroup.setName(jsonObject.getJSONObject("group")
						.getString("name"));
			} catch (Exception e) {
				weixinGroup = null;
				int errorCode = jsonObject.getInt("errcode");
				String errorMsg = jsonObject.getString("errmsg");
				log.error("创建分组失败 errcode:{} errmsg:{}", errorCode + "",
						errorMsg);
				e.printStackTrace();
			}
		}
		return weixinGroup;
	}

	/**
	 * 修改分組
	 * 
	 * @param accessToken
	 *            接口访问凭证
	 * @param groupId
	 *            分组ID
	 * @param groupName
	 *            修改后的分组名
	 * @return
	 */
	public static boolean updateGroup(String accessToken, int groupId,
			String groupName) {
		boolean result = false;
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=ACCESS_TOKEN";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
		// 需要提交的JSON数据
		String jsonData = "{\"group\":{\"id\":%d,\"name\":\"%s\"}}";
		JSONObject jsonObject = CommonUtil.httpRequest(requestUrl, "GET",
				String.format(jsonData, groupId, groupName));
		if (null != jsonObject) {
			int errorCode = jsonObject.getInt("errcode");
			String errorMsg = jsonObject.getString("errmsg");
			if (0 == errorCode) {
				result = true;
				log.error("修改分组成功 errcode:{} errmsg:{}", errorCode + "",
						errorMsg);
			} else
				log.error("修改分组失败 errcode:{} errmsg:{}", errorCode + "",
						errorMsg);
		}
		return result;
	}

	/**
	 * 移动用户分组
	 * 
	 * @param accessToken
	 *            接口访问凭证
	 * @param openId
	 *            用户标识
	 * @param groupId
	 *            分组Id
	 * @return
	 */
	public static boolean updateMemberGroup(String accessToken, String openId,
			int groupId) {
		boolean result = false;
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/members/update?access_token=ACCESS_TOKEN";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
		// 需要提交的JSON数据
		String jsonData = "{\"openid\":\"%s\",\"to_groupid\":%d}";
		JSONObject jsonObject = CommonUtil.httpRequest(requestUrl, "GET",
				String.format(jsonData, openId, groupId));
		if (null != jsonObject) {
			int errorCode = jsonObject.getInt("errcode");
			String errorMsg = jsonObject.getString("errmsg");
			if (0 == errorCode) {
				result = true;
				log.error("移动用户分组分组成功 errcode:{} errmsg:{}", errorCode + "",
						errorMsg);
			} else
				log.error("移动用户分组分组失败 errcode:{} errmsg:{}", errorCode + "",
						errorMsg);
		}
		return result;
	}

	public static void main(String[] args) {
		String accessToken = CommonUtil.getToken("appid", "appsecret")
				.getAccessToken();
		// 查询分组
		// List<WeixinGroup> groupList = getGroups(accessToken);
		// for (WeixinGroup weixinGroup : groupList) {
		// System.out.println(String.format("ID:%d 名称: %s 用户数: %d",
		// weixinGroup.getId(), weixinGroup.getName(), weixinGroup
		// .getCount()));
		// }
		// 创建分组
		// WeixinGroup group = createGroup(accessToken, "公司员工");
		// System.out.println(String.format("成功创建分组: %s id:%d", group.getName(),
		// group.getId()));
		// 修改分組
		// updateGroup(accessToken, 100, "同事");
		// 移动用户分组
		updateMemberGroup(accessToken, "asdfasdfasdfasdf", 100);
	}
}
